#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "bmp.h"
#include "lcd.h"
void bmp_display(lcd * s , int x0, int y0,const char * file_bmp)
{
    int fb_bmp = open(file_bmp,O_RDONLY);
    if(fb_bmp == -1)
    {
        perror("fb_bmp error");
        return ;
    }

    int width,height;
    short depth;
    
    unsigned char buf[4];
    lseek(fb_bmp,0x12,SEEK_SET);
    int red = read(fb_bmp,buf,4);
    if(red != 4)
    {
        perror("bmp read error");
        close(fb_bmp);
        return ;
    }
    width = (buf[3]<<24)|(buf[2]<<16) | (buf[1]<<8) |buf[0];

    lseek(fb_bmp,0x16,SEEK_SET);
    red = read(fb_bmp,buf,4);
    if(red != 4)
    {
        perror("bmp read error");
        close(fb_bmp);
        return ;
    }
    height = (buf[3]<<24)|(buf[2]<<16) | (buf[1]<<8) |buf[0];
    
    lseek(fb_bmp,0x1c,SEEK_SET);
    red = read(fb_bmp,buf,2);
    if(red != 2)
    {
        perror("bmp read error");
        close(fb_bmp);
        return ;
    }
    depth = (buf[1]<<8) |buf[0];

    //printf("w = %d h = %d d = %d\n",width,height,depth);

    int liezi,valid_w,sum;
    valid_w = abs(width) * depth / 8;
    liezi = 0;
    if(valid_w % 4)
    liezi = 4-valid_w % 4;
    int valid_sumw = liezi + valid_w;
    sum = valid_sumw * abs(height);

    unsigned char * pixel = malloc(sum);
    lseek(fb_bmp,54,SEEK_SET);
    red = read(fb_bmp,pixel,sum);
    if(red == -1)
    {
        perror("bmp read error");
        close(fb_bmp);
        free(pixel);
        return ;
    }


    unsigned char a,r,g,b;
    int x,y;int i = 0;
    for(y=0;y<abs(height);y++)
    {
        for(x=0;x<abs(width);x++)
        {
            b = pixel[i++];
            g = pixel[i++];
            r = pixel[i++];
            if(depth == 24)
            {
                a = 0x00;
            }
            else if(depth == 32)
            {
                a = pixel[i++];
            }
            int color = (a<<24) | (r<<16)| (g<<8) | b;
            hua_dian(s,width>0?x+x0:abs(width)-x-1+x0,height>0?abs(height)-y-1+y0:y+y0,color);
        }
        i = i+liezi;
    }
    close(fb_bmp);
    return ;
}
